import { useRouter } from "vue-router";
import {
  PropType,
  ref,
  watch,
  reactive,
  toRefs,
  inject,
  provide,
  onMounted,
  onBeforeMount,// 在组件挂载之前执行的函数
  nextTick
} from "vue";
import { common, webScoketObject, userinfo } from "/@/hooks/common";
// 引入公共js文件
import utils from "/@/assets/js/public/function";

import Wangeditor from "/@/components/pc/Wangeditor.vue";
// api 接口文件
import { getChatRecordApi } from "/@/api/components/pc/Drawer";

// 定义返回的类型
interface dataRef {
  close: () => void;
  showLogin: () => void;
  enterDialog: (username: string,userlogo:string, id: string, fd: any, type: any)=>void;
  goBackUserList:()=>void;
  getWangEditorReplayValue:(str:string)=>void;
  sendButtonClick:()=>void;
  
}
export default {
  name: "Drawer",
  /**
   * @name: 使用组件
   * @author: camellia
   * @email: guanchao_gc@qq.com
   * @date: 2021-02-25 
   */
  components: {
    Wangeditor,
  },
  // VUE3语法 setup函数
  // setup官方文档:https://www.vue3js.cn/docs/zh/guide/composition-api-setup.html#参数
  setup(props: any, content:any): dataRef 
  {
    const router = useRouter();

    /**
     * @name: 声明data
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-10 
     */
    const data = reactive({
      // 抽屉显示状态
      drawerShow: common.drawerShow,
      // webscoket对象
      // scoketObject: new WebSocket('wss://blog.guanchao.site/websocket/'),
      // scoketObject : new WebSocket('ws://127.0.0.1:7001/api/websocket/'+Math.floor((Math.random() * 100) + 1)),
      // scoketObject : new WebSocket(""),
      scoketObject: undefined,
      // 登录框显示状态
      menuShow:0,
      // webscoket显示状态
      webscoketStatus:'login',
      // 已连接用户列表
      webscoketUserList:{},
      // 被动聊天用户昵称
      to_user_name:'',
      // 被动聊天用户id(已加密)
      to_user_id:'',
      // 被动聊天用户头像
      to_user_logo:'',
      // 主动聊天用户id
      from_user_id:userinfo.userid,
      // 主动聊天用户头像
      from_user_logo: userinfo.figureurl,
      // webscoket 链接主键
      webscoketFD:'',
      // 聊天类型
      webscoketType:'',
      // wangeditor 显示标识
      editorShowSign:false,
      // 要发送的消息
      message:'',
      // 聊天记录列表
      chatRecordList: [{
        classs: '',
        msg: '',
        addtime: '',
        userlogo:''
      }],
      // 未读消息总数
      totalUnReadNumber:0,
    });

    /**
     * @name: 监听公共状态栏值变化(控制抽屉显示)
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-10 
     */
    watch(
      () => common.drawerShow,
      () => {
        data.drawerShow = common.drawerShow;   
        // 如果抽屉打开状态，获取在线用户列表
        if (data.drawerShow)
        {
          // 清空聊天记录
          data.chatRecordList = [{class: '',  msg: '', addtime: '',userlogo:''}];
          if(userinfo.userid)
          {
            data.webscoketStatus = 'webscoketList';
          }
          else
          {
            data.webscoketStatus = 'login';
          }
        }    
      }
    );
    /**
     * @name: 监听有用户id时，创建webscoket连接
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-04-06 
     */
    watch(
      () => userinfo.userid,
      () => {
        // 清除定时器(销毁之前链接的webscoket)
        clearInterval(webScoketObject.timer);
        if (userinfo.userid)
        {
          data.webscoketStatus = 'webscoketList';
          // 初始化客户端套接字并建立连接
          // var sock = new WebSocket("wss://guanchao.site/websocket/");
          // var sock = new WebSocket("wss://l.guanchao.site/websocket");
          // var sock = new WebSocket("ws://1.15.157.156:9502");
          // data.scoketObject = new WebSocket('wss://blog.guanchao.site/websocket/');
          let url = "";
          if(import.meta.env.VITE_APP_LANGUAGE == 'PHP')
          {
            url = import.meta.env.VITE_APP_WEBSOCKET_URL_PHP;
          }
          else
          {
            url = import.meta.env.VITE_APP_WEBSOCKET_URL_CLOUD+localStorage.getItem("webscoketID");
            // url = import.meta.env.VITE_APP_WEBSOCKET_URL_JAVA+localStorage.getItem("webscoketID");
          }
          data.scoketObject = new WebSocket(url);
          console.log(data.scoketObject)
          /**
           * @name: 连接建立时触发
           * @author: camellia
           * @email: guanchao_gc@qq.com
           * @date: 2021-04-06 
           */
          data.scoketObject.onopen = (event: any) => {
            console.log("Connection open ...");
            // 初始化时发送请求，获取已连接用户列表
            sendMessage('ping', userinfo.userid, userinfo.userid);
            //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
            webScoketObject.timer = window.setInterval(function () {
              // console.log('每隔5秒钟发送一次心跳');
              // 发送消息
              sendMessage('ping', userinfo.userid, userinfo.userid);
            }, 5000);
          };
          /**
           * @name: 接收到服务端推送时执行
           * @author: camellia
           * @email: guanchao_gc@qq.com
           * @date: 2021-04-06 
           */
          data.scoketObject.onmessage = (event: any) => {
            // 后端返回值
            var param = JSON.parse(event.data);
            // 返回参数类型
            var type = param.type;
            console.log(param)
            // 未读消息总数
            if (param.totalUnReadNumber != undefined && webScoketObject.totalUnReadNumber != param.totalUnReadNumber)
            {
              webScoketObject.totalUnReadNumber = param.totalUnReadNumber;
              data.totalUnReadNumber = param.totalUnReadNumber;
            }
            if (param.list != data.webscoketUserList && type == 'ping')
            {//心跳
              // 用户列表
              data.webscoketUserList = param.list;
            }
            else if (type == 'AIchat')
            {//ai聊天
              let json = {
                class: 'left',
                msg: param.response.answer,
                addtime: utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
                userlogo: data.to_user_logo
              };
              // 写入聊天记录列表
              data.chatRecordList.push(json);
              // 滚动条滚动至最下
              goScrollAnyHeight();
            }
            else if (type == 'userchat')
            {//用户聊天
              let json = {
                classs: 'left',
                msg: param.response.answer,
                addtime: utils.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss'),
                userlogo: data.to_user_logo
              };
              // 写入聊天记录列表
              data.chatRecordList.push(json);
              // 滚动条滚动至最下
              goScrollAnyHeight();
            }
            else if(type == 'message')
            {// java websocket

            }
            // console.log(data.webscoketUserList);
            // console.log("webscoket 接收到返回消息！");
          };
          /**
           * @name: 连接关闭时触发
           * @author: camellia
           * @email: guanchao_gc@qq.com
           * @date: 2021-04-06 
           */
          data.scoketObject.onclose = (event: any) => {
            // webscoket 关闭之后 清除 心跳 定时器
            // clearInterval(webScoketObject.timer);
            console.log("Connection closed ...");
          };
          /**
           * @name: 出错时触发
           * @author: camellia
           * @email: guanchao_gc@qq.com
           * @date: 2021-04-06 
           */
          data.scoketObject.onerror = (event: any) => {
            // webscoket 关闭之后 清除 心跳 定时器
            clearInterval(webScoketObject.timer);
            console.log('Error occured: ' + event.data);
          };

        }
      }
    );

    /**
     * @name: 生命周期，页面挂载成功之后
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-04-15 
     * @param:	data	type	description
     * @return:	data	type	description
     */
    onMounted( ()=>{
      // 监听键盘事件
      document.onkeydown = function (event) {
        if (event.altKey && event.keyCode == 82)
        {
          sendButtonClick();
          // 点击发送按钮状态改为true;
          webScoketObject.is_click_send = true;
        }
      }
    });

    /**
     * @name: 点击发送消息按钮
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-04-10 
     * @param:	data	type	description
     * @return:	data	type	description
     */
    const sendButtonClick = () =>{
      if (!data.message)
      {
        utils.alertMsg(2000, '发送消息不能为空！'); return;
      }
      // 点击发送按钮状态改为true;
      webScoketObject.is_click_send = true;
      // 将消息拼成json存入聊天记录中
      let json = {
        class:'right',
        msg: data.message,
        addtime: utils.dateFormat(new Date(),'yyyy-MM-dd hh:mm:ss'),
        userlogo: userinfo.figureurl
      };
      // 写入聊天记录列表
      data.chatRecordList.push(json);
      // 滚动条滚动至最下
      goScrollAnyHeight();
      // 调用公共方法将消息发送给服务器
      sendMessage(data.webscoketType, userinfo.userid, data.to_user_id, data.message, data.webscoketFD);
    }

    /**
     * @name: 发送消息给webscoket
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-04-08 
     * @param:	type	string	消息类型
     * @param:	from_user_id	int	发送消息用户
     * @param:	to_user_id	int	接受消息用户
     * @param:	msg	string	要发送的消息
     * @param:	fd	int	webscoket链接主键
     */
    const sendMessage = (type: any, from_user_id:any ,to_user_id:any,msg:string='',fd:any='') => {
      // readyState 链接状态：0：连接中、1：已连接，可通讯、2：正在关闭、3：已关闭
      if (data.scoketObject.readyState != 1) 
      {
        console.log('网络连接已断开！');
        // 返回断网提示语，继续使用请重新加载页面
        utils.alertMsg(5000, '您已掉线，请刷新页面后重新打开！');
        clearInterval(webScoketObject.timer); return;
      }
      var message = {
        "type": type,
        "from_user_id": from_user_id,
        'to_user_id': to_user_id,
        'msg': msg,
        'fd': fd
      };
      // console.log(message);
      // console.log(data.scoketObject);
      data.scoketObject.send(JSON.stringify(message));
    };

    /**
     * @name: 进入聊天对话框页
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-04-08 
     */
    const enterDialog = (username:string, userlogo:string,id:string, fd:any,type:any) => {
      data.webscoketStatus = 'webscoketChat';
      data.to_user_name = username;
      data.to_user_logo = userlogo;
      data.to_user_id = id;
      data.webscoketFD = fd;
      data.webscoketType = type;

      console.log(data.webscoketType)

      // 聊天记录清空
      data.chatRecordList = [];

      // console.log(data.webscoketType)
      if (data.webscoketType != 'AIchat')
      {
        let param = {
          'to_user_id': data.to_user_id,
          'from_user_id': userinfo.userid
        }
        // 获取聊天记录
        getChatRecordApi(param).then(function (response: any) {
          data.chatRecordList = response.list;
          // console.log(data.chatRecordList);
          // 滚动条滚动至最下
          goScrollAnyHeight();
        });
      }
    }

    /**
     * @name: 滚动条滚动至任意高度
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-04-13 
     */
    const goScrollAnyHeight = (val:number=500000) =>{
      // 此处为操作 DOM 相当于vue2 中的 this.$nextTick
      nextTick(() => {
        var chat = document.getElementById('chat-dialog');
        if (chat) {
          chat.scrollTop = val;
        }
      });
    }

    /**
     * @name: 返回用户列表页
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-04-08 
     */
    const goBackUserList = () => {
      data.webscoketStatus = 'webscoketList';
    }

    /**
     * @name: 获取评论回复wangeditor数据
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-27 
     */
    const getWangEditorReplayValue = (str: string) => {
      let string = str.replace('p', "span");
      data.message = string.replace('/p', "/span");
    }
    
    /**
     * @name: 关闭组件
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-10 
     */
    const close = () => {
      data.drawerShow = false;
      common.drawerShow = data.drawerShow;
      utils.setLabelStyle('body', '');
    }

    /**
     * @name: 显示登录框
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-19 
     */
    const showLogin = () => {
      // 关闭抽屉组件
      close();
      data.menuShow = 1;
      // 子组件向父组件传值
      content.emit('showMenuByChild', data.menuShow);
      // 菜单显示标识（is_menu,is_search,is_login）
      common.menuSign = 'is_login';
      // 获取当前连接
      common.currectUrl = window.location.href;
      utils.setLabelStyle('body', 'overflow-y: hidden;');
    }
    /**
     * @name: 将data绑定值dataRef
     * @author: camellia
     * @email: guanchao_gc@qq.com
     * @date: 2021-01-10 
     */
    const dataRef = toRefs(data);
    return {
      close,
      showLogin,
      enterDialog,
      getWangEditorReplayValue,
      goBackUserList,
      sendButtonClick,
      ...dataRef
    }
  },
}

